﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System.Web;
using System.Configuration;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// WMS出库信息_同步跟单猿
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WMSShipInfoToRaipiotController : ControllerBase
    {
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_gz;
        private readonly ILogger _logger;


        public WMSShipInfoToRaipiotController(ILogger<WMSShipInfoToRaipiotRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {

            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_gz = _configuration.GetConnectionString("WMSDbConnection_GZ");
            _logger = loggerFactory.CreateLogger<WMSShipInfoToRaipiotController>();

        }

        /// <summary>
        /// WMS出库信息_同步跟单猿
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostWMSShipInfoToGDY([FromBody] WMSShipInfoToRaipiotRequestDto strparm)
        {
            string factory_code = strparm.factory_code;
            string  strMsg = "";
            object log = "";
            string wms_con = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            List<string> restrSqlList = new List<string>();
            WaybillInfoSendWMSResponseDto re = new WaybillInfoSendWMSResponseDto();
            WaybillInfoSendWMSRequestDto pus = new WaybillInfoSendWMSRequestDto();

            if (factory_code== "C01")
            {
                wms_con = con_zh;
            }
            else if (factory_code == "B01")
            {
                wms_con = con_qh;
            }
            else if (factory_code == "E01")
            {
                wms_con = con_yb;
            }
            else if (factory_code == "G01")
            {
                wms_con = con_gz;
            }
            else
            {

            }

            try
            {
                if (wms_con != "")
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                    dic = new Dictionary<string, string>(); //查询公用dic
                    dic.Add("organization", "");//查询参数
                    DataTable push_dt = MethodHelp.GetOutsideTableInfo("TMS0035", dic, wms_con, con);//获取推送数据
                    if (push_dt.Rows.Count > 0)
                    {
                        Dictionary<string, string> urldic = new Dictionary<string, string>(); //查询公用dic
                        urldic = new Dictionary<string, string>(); //查询公用dic
                        urldic.Add("function_description", "跟单猿_Token获取");//查看URL配置表地址描述
                        DataTable token_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                        if (token_dt.Rows.Count > 0)
                        {
                            var reAgv2 = DB.httpGet(token_dt.Rows[0]["interface_url"].ToString(), "", "否");
                            RaipiotTokenResponseDto psp = JsonConvert.DeserializeObject<RaipiotTokenResponseDto>(reAgv2);
                            if (psp.status == 200)
                            {
                                foreach (DataRow item in push_dt.Rows)
                                {

                                    restrSqlList = new List<string>();//回写WMS运单扫码表
                                    ToRaipiotInfoRequestDto out_info = new ToRaipiotInfoRequestDto();
                                    List<ToRaipiot_DetailRequestDto> out_info_de = new List<ToRaipiot_DetailRequestDto>();
                                    out_info.transportOrderNo = item["shipping_order_no"].ToString();
                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("shipping_order_no", item["shipping_order_no"].ToString());//查询参数
                                    DataTable de_orderinfo= MethodHelp.GetOutsideTableInfo("TMS0057", dic, wms_con, con);
                                    if (de_orderinfo.Rows.Count>0)
                                    {
                                        string sysid = "";
                                        if (de_orderinfo.Rows[0]["sales_order_no"].ToString()== "1301")
                                        {
                                            sysid = "TMS0056";
                                        }
                                        else
                                        {
                                            sysid = "TMS0036";
                                        }
                                        DataTable de_dt = MethodHelp.GetOutsideTableInfo(sysid, dic, wms_con, con);//获取推送数据
                                        if (de_dt.Rows.Count > 0)
                                        {
                                            foreach (DataRow row in de_dt.Rows)
                                            {
                                                string order_no = "";
                                                string address_id = "";
                                                if (row["crm_no"].ToString() == "")
                                                {
                                                    order_no = row["source_no"].ToString();
                                                    address_id = row["address_id"].ToString();//硅棒业务，获取地址ID
                                                }
                                                else
                                                {
                                                    order_no = row["crm_no"].ToString();
                                                }

                                                out_info_de.Add(new ToRaipiot_DetailRequestDto
                                                {
                                                    goodsName = row["material_name"].ToString(),
                                                    goodsCode = row["material_code"].ToString(),
                                                    goodsTotal = DB.ToDecimal(row["material_amount"].ToString()),
                                                    orderNo = order_no,
                                                    saleNo = row["source_no"].ToString(),
                                                    subOrderNo = row["sales_order_line_no"].ToString(),
                                                    subSaleNo = row["source_item_code"].ToString(),
                                                    deliveryNoteNo = row["waybill_no"].ToString(),
                                                    caseNo = "",
                                                    palletNo = "",
                                                    receiveTransportOrderLoadId = address_id//地址ID回传

                                                });


                                                dic = new Dictionary<string, string>(); //查询公用dic
                                                dic.Add("shipping_order_no", item["shipping_order_no"].ToString());
                                                dic.Add("sales_order_line_id", row["source_item_code"].ToString());
                                                string strSQL = MethodHelp.GetTranSQL("TMS0037", dic, con);//转换插入任务执行明细表SQL语句
                                                if (strSQL == "")
                                                {
                                                    strMsg = "TMS0037,Parameter conversion failed";
                                                }
                                                else
                                                {
                                                    restrSqlList.Add(strSQL.ToString());
                                                }
                                            }
                                            if (out_info_de.Count > 0)
                                            {
                                                out_info.transportTrackGoodsRequests = out_info_de;

                                                urldic = new Dictionary<string, string>(); //查询公用dic
                                                urldic.Add("function_description", "跟单猿_运单出库信息回写");//查看URL配置表地址描述
                                                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                                if (url_dt.Rows.Count > 0)
                                                {
                                                    string jsonText = JsonConvert.SerializeObject(out_info);
                                                    var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, psp.data.token, "是");
                                                    ToRaipiotInfoResponseDto psp2 = JsonConvert.DeserializeObject<ToRaipiotInfoResponseDto>(reAgv);
                                                    if (psp2.status != 200)
                                                    {
                                                        strMsg = strMsg + "-" + "跟单猿 ERR:" + "运单：" + item["shipping_order_no"].ToString() + psp2.message;
                                                    }
                                                    else
                                                    {
                                                        if (restrSqlList.Count > 0)
                                                        {
                                                            bool A = DB.ExecuteNoQueryTran(restrSqlList, wms_con);
                                                            if (A)
                                                            {

                                                            }
                                                            else
                                                            {
                                                                strMsg = "HandleTaskUpdate  Database update failed";
                                                            }
                                                        }

                                                    }
                                                }
                                            }

                                        }
                                    }

                                  

                                }
                            }
                           
                        }                    
                    }
                }
               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code = 0;
               
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
